/***FD***/
var C = function () { return {} }();
C.Dom = function () {
    return {
        setDisabled: function (selector, enabled, notclear) {
            if (enabled) {
                $(selector).removeAttr('disabled');
            }
            else {
                $(selector).attr('disabled', 'disabled');
                if (!notclear) {
                    $(selector).val('');
                }
            }
        },
        setVisibility: function (selector, visible) {
            if (visible) {
                $(selector).css('visibility', 'visible');
            }
            else {
                $(selector).css('visibility', 'hidden');
            }
        },
        setDisplay: function (selector, visible) {
            if (visible) {
                $(selector).show();
            }
            else {
                $(selector).hide();
            }
        },
        getCheckBoxHtml: function (value, text, id) {
            return '<label><input type="checkbox" value="' + value + '" ' + (id ? 'id="' + id + '"' : '') + '/> ' + text + '</label>';
        },
        getRadioHtml: function (name, value, text) {
            return '<label><input type="radio" value="' + value + '" name="' + name + '"/> ' + text + '</label>';
        },
        getSelectOption: function (value, text) {
            return '<option value="' + value + '">' + text + '</option>';
        }
    };
}();
C.Validate = function () {
    function updateAndShow(selector, msg) {
        $(selector).poshytip('update', msg);
        $(selector).poshytip('show');
    }
    return {
        regs: {//此部分直接取正则验证会有问题，待解决
            'float': /^\d+(\.\d+)?$/,
            'mobie': /^(13|14|15|18)\d{9}$/,
            'zipCode': /^\d{6}$/,
            'number': /^\d+$/,
            'char': /^[a-zA-Z]+$/,
            'email': /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
            'idCard': /(^\d{15}$)|(^\d{17}(\d|x|X)$)/,
            'date': /((^((1[8-9]\d{2})|([2-9]\d{3}))(-)(10|12|0?[13578])(-)(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))(-)(11|0?[469])(-)(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))(-)(0?2)(-)(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)(-)(0?2)(-)(29)$)|(^([3579][26]00)(-)(0?2)(-)(29)$)|(^([1][89][0][48])(-)(0?2)(-)(29)$)|(^([2-9][0-9][0][48])(-)(0?2)(-)(29)$)|(^([1][89][2468][048])(-)(0?2)(-)(29)$)|(^([2-9][0-9][2468][048])(-)(0?2)(-)(29)$)|(^([1][89][13579][26])(-)(0?2)(-)(29)$)|(^([2-9][0-9][13579][26])(-)(0?2)(-)(29)$))/
        },
        init: function (selector, tipData) {
            $(selector).poshytip(tipData);
            $(selector).focus(function () { $(this).poshytip('destroy'); });
        },
        destory: function (selector) {
            $(selector).poshytip('destroy');
        },
        chkEmpty: function (selector, msg) {
            var v = C.Validate.trimValue(selector);
            var val = v != '';
            if (!val) {
                updateAndShow(selector, msg);
            }
            return val;
        },
        chkRegex: function (selector, reg, msg) {
            var v = C.Validate.trimValue(selector);
            var val = reg.test(v);
            if (!val) {
                updateAndShow(selector, msg);
            }
            return val;
        },
        trimValue: function (selector) {
            var v = $.trim($(selector).val());
            $(selector).val(v);
            return v;
        },
        notice: function (selector, msg) {
            updateAndShow(selector, msg);
        }
    };
}();

C.Parse = function () {
    return {
        parseDate: function (dateStr) {
            var date = null;
            if (typeof (dateStr) == 'string' /*&& C.Validate.regs.date.test(dateStr)*/) {
                date = new Date(dateStr.replace(/-/g, "/"));
            }
            return date;
        }
    }
}();
var oGlobalData = {};
(function ($) {
    $.fn.airPortSelect = function (arg, method) {
        var container = $(this);
        var allChks = null;
        var setting = {
            idSeed: 'AirPortSelect', //id种子
            title: '', //标题
            titleClass: '', //标题样式
            titleIcon: '', //标题图标,

            airLineData: [], //机场数据,格式[{Key:'',Label:'',Data:[{Key:'',Label:'',Data:[{Key:'',Label:'',Data:''}]}]},{Key:'',Label:'',Data:[{Key:'',Label:'',Data:[{Key:'',Label:'',Data:''}]}]}]
            airLineFilters: '',//哪些机场需要构建html，与airLineData顺序对应，取到0时表示需要构建境内html，取到1时表示需要构建境外html，取到2时表示需要构建全球html
            airPortText: function (key, name) { return key + ' - ' + name; }, //显示的机场文字
            hightClass: '', //高亮样式
            searchInputClass: '', //查询输入框样式
            searchClass: '', //查询按钮样式
            allSelectedClass: '', //全选样式
            reverseSelectedClass: '', //反选样式
            onFastAirPortSelected: function () { },
            cabinEnabled: false, //是否包含舱位
            cabinData: [], //特殊舱位，字符串数组
            onFastCabinSelected: function () { },
            domesticKey: '0',//境内
            needSortedCheck : 100 //启用排序算法 关闭：false 开启：估计的平衡点，例如100
        }
        if (typeof method == "string") {
            switch (method) {
                case 'selectAirPort': //快速选择机场，此时arg为三字码字符串(以/分隔)
                case 'fastFind'://快速查找
                    if (typeof arg == "string" && $.trim(arg) != '') {
                        arg = arg.replace(/\s/g, '').toUpperCase();
                        if (arg.substr(arg.length - 1) != '/') {
                            arg += '/';
                        }
                        if (/^([a-zA-Z]{3}\/)+$/g.test(arg)) {
                            var arr = arg.split(/[\/]/g);
                            arr.sort();//排序
                            var ptl2 = $('.tab_lv2', container);
                            if (allChks == null) {
                                if (container.find('.tab_lv0').attr('dataType') == '0') {//境内
                                    allChks = $('.tab_lv2 :checkbox', container);
                                    ptl2 = $('.tab_lv2', container);
                                } else {
                                    allChks = $('.tab_lv4 :checkbox', container);
                                    ptl2 = $('.tab_lv4', container);
                                }
                                allChks.sort(function (x, y) {
                                    if (x.value >= y.value) {
                                        return 1;
                                    }
                                    else {
                                        return -1;
                                    }
                                });//排序
                            }
                            var ds = $('[ref=unknowAP]', container);
                            var d = ds.filter('dd');
                            var sp = $('div.tab_selected:eq(0)>div>div>font', container);
                            sp.hide();
                            var allAirports = $(container).data('aaps');
                            var allCharIdxs = $(container).data('cIdxs');
                            var startIndex = 0;//第一个位置
                            var fixNum = 0;
                            for (var i = 0; i < arr.length; i++) {
                                if (arr[i] == '') {
                                    continue;
                                }
                                var nowChar = allCharIdxs[arr[i].charCodeAt(0) - 65];
                                startIndex = Math.max(startIndex, nowChar.I);
                                fixNum = Math.max(fixNum, nowChar.F);
                                for (var j = startIndex; j < allAirports.length; j++) {
                                    startIndex++;
                                    var af = allAirports[j];
                                    if (af.F) {
                                        fixNum++;
                                    }
                                    if (arr[i] > af.A) {
                                        continue;
                                    }
                                    else if (arr[i] < af.A) {//未找到节点，但无需继续寻找，属于未知城市
                                        if (method == 'fastFind') {
                                            return null;
                                        }
                                        startIndex--;
                                        if (startIndex < 0) {
                                            startIndex = 0;
                                        }
                                        if (af.F) {
                                            fixNum--;
                                        }
                                        ds.show();
                                        if (d.text().indexOf(arr[i]) < 0) {
                                            d.html(d.text() + arr[i] + '/');
                                        }
                                        //console.info('AirLine:'+ af.A +' Filter:'+af.F + ' Index:' + startIndex + ' FNums:' + fixNum);
                                        break;
                                    }
                                    else {//找到节点，终止内部循环
                                        if (method == 'fastFind') {
                                            if (!af.F) {
                                                return allChks[j - fixNum];
                                            }
                                            else {
                                                return null;
                                            }
                                        }
                                        if (!af.F) {//非过滤
                                            $(allChks[j - fixNum]).attr('checked', 'checked');
                                        }
                                        break;
                                    }
                                }
                            }
                            ptl2.each(function (i, n) {
                                $(':checkbox:checked:eq(0)', n).click().attr('checked', 'checked');

                            }); //更新选中机场部分
                            var idx = $(container).airPortSelect(null, 'getSelectedIndex');
                            $('div.tab_selected dl:not(:last)', container).filter(':not(:eq(' + idx + '))').hide(); //隐藏被checkbox显示出来的不属于当前选项卡的dl
                            if ($.trim(d.text()) == '' && $('div.tab_lv1:eq(' + idx + ') :checked:eq(0)', container).length == 0) {
                                sp.show(); //显示未选择的提示信息
                            }
                        }
                    }
                    break;
                case 'selectCabin': //快速选择舱位，以/分隔
                    if ($('.tab_cabin', container).length > 0 && typeof arg == "string" && $.trim(arg) != '') {
                        arg = $.trim(arg).toUpperCase();
                        if (arg.substr(arg.length - 1) != '/') {
                            arg += '/';
                        }
                        var arr = arg.split(/[\/]/g);
                        var ptc = $('.tab_cabin', container);
                        for (var i = 0; i < arr.length; i++) {
                            if (arr[i] == '') {
                                continue;
                            }
                            $(':checkbox[value=' + arr[i] + ']', ptc).attr('checked', 'checked');
                        }
                        getSelectedCabinText();
                    }
                    break;
                case 'unSelectAirPort': //指定选项卡下的所有机场取消选定
                    var i = parseInt(arg);
                    if (i != NaN) {
                        var pd = $('div.tab_lv1:eq(' + i + ')', container);
                        pd.find(':checkbox').removeAttr('checked');
                        pd.find('li a').each(function (i, n) {
                            $(n).html($(n).text().replace('*', ''));
                        });
                        var dv = $('div.tab_selected>.mt>div', container);
                        var dls = $('dl', dv);
                        var ndl = dls.filter(':eq(' + i + ')');
                        ndl.hide();
                        $('*', ndl).hide();
                        $('dd', ndl).empty();
                        if ($('dd', dls.filter(':last')).text() == '' && $(container).airPortSelect(null, 'getSelectedIndex') == i) {
                            $('font:eq(0)', dv).show();
                        }
                    }
                    break;
                case 'selectedIndex': //选中第几个选项卡
                case 'hide': //隐藏第几个选项卡
                case 'show': //显示第几个选项卡
                case 'isShow'://第几个选项卡是否显示
                    var i = parseInt(arg);
                    if (i != NaN) {
                        var l = container.find('ul._ul0 li:eq(' + i + ')');
                        if (method == 'show') {
                            l.show();
                        }
                        else if (method == 'hide') {
                            l.hide();
                        }
                        else if (method == 'isShow') {
                            l.is(':visible');
                        }
                        else {//selectedIndex
                            l.find('a').click();
                        }
                    }
                    break;
                case 'getSelectedIndex': //获取选中的是第几个选项卡
                    var idx = 0;
                    var ulas = $(container).find('ul._ul0 a');
                    for (var i = 0; i < ulas.length; i++) {
                        if ($(ulas[i]).hasClass('selected')) {
                            idx = i;
                            break;
                        }
                    }
                    return idx;
                case 'getSelectedAirPort': //获取已选择的机场，可以指定只获取特定索引对应的机场，包含未知机场
                case 'getSelectedCabin': //获取已选择的舱位
                    var d = '';
                    var prt;
                    if (method == 'getSelectedCabin') {
                        prt = $('div.tab_cabin', container);
                    }
                    else {
                        var sl = 'div.tab_lv2';
                        if (container.find('.tab_lv0').attr('dataType') != '0') {//非境内
                            sl = 'div.tab_lv4';
                        }
                        if (typeof (arg) == 'Number') {//只获取指定索引选项卡对应的机场
                            sl += ':eq(' + parseInt(arg) + ')';
                        }
                        prt = $(sl, container);
                    }
                    if (prt.length > 0) {
                        $(':checked', prt).each(function (i, n) {
                            d += $(n).val() + '/';
                        });
                    }
                    if (method == 'getSelectedAirPort') {
                        d += $('dd[ref=unknowAP]', container).text();
                    }
                    return d;
                case 'reInit':
                    var oArgs = $(container).data('args');
                    if (oArgs != null) {

                        if (arg != oArgs.airLineFilters) {
                            oArgs.airLineFilters = arg;
                            $(container).airPortSelect(oArgs);
                        }
                    }
                    break;
                case 'getAirPortSelectExceptView':
                    return changeView();
                case 'getAirPortSelectExcept':
                    return getOSelectExcept();    
                case 'initAirPortSelectExcept':
                    var oSelect = parseSelectExceptCode(arg.select);//已选内容
                    var oExcept = parseSelectExceptCode(arg.except);//排除内容
                    var unKnown = '';//未知机场
                    var needSortedCheck = container.data('args').needSortedCheck;

                    if (getDataType() == '0') {//境内
                        if (getTopCode() == oSelect.topCode) {
                            container.find('div.div_lvl_0 :checkbox').attr('checked', 'checked');
                            container.find('div.tab_lv2 :checkbox').attr('checked', 'checked');
                            if (needSortedCheck && oExcept.airportArray.length > needSortedCheck) {
                                sortedCheck(oExcept.airportArray, container.find('div.tab_lv2 :checkbox'), false);
                            } else {
                                for (var i = 0; i < oExcept.airportArray.length; i++) {//排除的机场
                                    var code = oExcept.airportArray[i];
                                    container.find('div.tab_lv2 :checkbox[value="' + code + '"]').removeAttr('checked');
                                }
                            }
                            for (var i = 0; i < oSelect.airportArray.length; i++) {//境内选中的场合，选择的机场必为未知机场
                                var code = oSelect.airportArray[i];
                                unKnown += code + '/';
                            }
                        } else {
                            if (needSortedCheck && oSelect.airportArray.length > needSortedCheck) {
                                sortedCheck(oSelect.airportArray, container.find('div.tab_lv2 :checkbox'), true);
                            } else {
                                for (var i = 0; i < oSelect.airportArray.length; i++) {
                                    var code = oSelect.airportArray[i];
                                    var chk = container.find('div.tab_lv2 :checkbox[value="' + code + '"]');
                                    if (chk) {
                                        chk.attr('checked', 'checked');
                                    } else {//已选的不存在机场即为未知机场
                                        unKnown += code + '/';
                                    }
                                }
                            }
                        }
                        //container.find('div.tab_selected dl[ref=unKnown] dd').html(unKnown);
                        updateOSelectExcept();
                    } else {
                        if (getTopCode() == oSelect.topCode) {
                            container.find('div.div_lvl_0 :checkbox').attr('checked', 'checked');
                            container.find('div.tab_lv2 :checkbox').attr('checked', 'checked');
                            if (needSortedCheck && oExcept.countryArray.length > needSortedCheck) {
                                sortedCheck(oExcept.countryArray, container.find('div.tab_lv2 :checkbox'), false);
                            } else {
                                for (var i = 0; i < oExcept.countryArray.length; i++) {//排除的国家
                                    var code = oExcept.countryArray[i];
                                    container.find('div.tab_lv2 :checkbox[value="' + code + '"]').removeAttr('checked');
                                }
                            }
                            updateOSelectExcept({ 'type': 'top', 'isCheck': true, 'skip': true });
                            updateOSelectExcept({ 'type': 'country', 'isCheck': false, 'values': oExcept.countryArray.join('/'), 'skip': true });
                            updateOSelectExcept({ 'type': 'airport', 'isCheck': false, 'values': oExcept.airportArray.join('/') });

                        } else {
                            if (needSortedCheck && oSelect.countryArray.length > needSortedCheck) {
                                sortedCheck(oSelect.countryArray, container.find('div.tab_lv2 :checkbox'), true);
                            } else {
                                for (var i = 0; i < oSelect.countryArray.length; i++) {//选中的国家
                                    var code = oSelect.countryArray[i];
                                    container.find('div.tab_lv2 :checkbox[value="' + code + '"]').attr('checked', 'checked');
                                }
                            }
                            updateOSelectExcept({ 'type': 'country', 'isCheck': true, 'values': oSelect.countryArray.join('/'), 'skip': true });
                            updateOSelectExcept({ 'type': 'airport', 'isCheck': true, 'values': oSelect.airportArray.join('/'), 'skip': true });
                            updateOSelectExcept({ 'type': 'airport', 'isCheck': false, 'values': oExcept.airportArray.join('/') });
                        }
                        //初期化，洲际里的国家全选中，洲际选中
                        container.find('._ul1').find('input:checkbox').each(function () {
                            var ref = $(this).next().attr('href');
                            if (container.find(ref).find('input:checkbox').length ==
                                container.find(ref).find('input:checkbox:checked').length) {
                                $(this).attr('checked', 'checked');
                            }
                        });
                    }

                    setView();
                    updateSelectMark();
                    setTransDisabled({ 'type': 'top', 'isCheck': isTopChecked() });//中转的场合不能选择排除
                    break;
                case 'fastSearchCountryAirport':
                    var lv0 = container.find('div.tab_lv0');

                    var oSelect = arg;//已选内容

                    if (getDataType() == '0') {//境内
                        for (var i = 0; i < oSelect.airportArray.length; i++) {
                            var code = oSelect.airportArray[i];
                            container.find('div.tab_lv2 :checkbox[value="' + code + '"]').attr('checked', 'checked');
                        }
                        updateOSelectExcept();
                    } else {
                        var totalCountrys = [];
                        for (var i = 0; i < oSelect.countryArray.length; i++) {
                            var countryCode = oSelect.countryArray[i];
                            container.find('div.tab_lv2 :checkbox[value="' + countryCode + '"]').attr('checked', 'checked');
                            totalCountrys.push(countryCode);
                        }
                        updateOSelectExcept({ 'type': 'country', 'isCheck': true, 'values': totalCountrys.join('/') });
                        var data = getOData();
                        var airports = [];
                        for (var i = 0; i < oSelect.airportArray.length; i++) {
                            var airportCode = oSelect.airportArray[i];
                            var countryCode = oGlobalData.airport[airportCode];
                            if (isTopChecked() && data[countryCode].c == '0') {
                                //顶层选中，国家排除，则机场不能选择
                            } else {
                                totalCountrys.push(countryCode);//将添加的国家和添加的机场对应的国家合并
                                airports.push(oSelect.airportArray[i]);
                            }
                        }
                        updateOSelectExcept({ 'type': 'airport', 'isCheck': true, 'values': airports.join('/') });

                        var countryId = container.find('.air_list_country').attr('key');
                        if (countryId) {
                            if (totalCountrys.join('').indexOf(countryId) == -1) {//当前显示的机场不在处理范围里
                                return;
                            }
                            hideAirports();
                            setAirport(countryId);
                        }
                    }
                    setView();                    
                    updateSelectMark();
                    break;
            }
        }
        else {
            arg = $.extend({}, setting, arg);
            $(container).data('args', arg);//所有的机场数据

            if (arg.airLineFilters == '') {
                return;
            }

            var h = '<div class="' + arg.titleClass + '"><h3><img style="width:22px;height:22px;" alt="' + arg.title + '" src="' +
                        arg.titleIcon + '"/>' + arg.title + '</h3></div><div class="tab"><div class="tab_lv0" dataType="' + arg.airLineFilters + '" dataIndex="' + arg.dataIndex + '"><ul class="_ul0">';
            var h1 = ''; //主体
            var ha = ''; //境内：空，境外全球：机场
            var allAirports = new Array();
            //for (var i = 0; i < arg.airLineData.length; i++) {                
            var i = parseInt(arg.airLineFilters);
            var hIdSeed = arg.idSeed + '_' + i;
            var d0 = arg.airLineData[i];
            allAirports.push(getArray(d0));

            if (!oGlobalData.result) {//储存每个板块的选中排除最终返回结果
                oGlobalData.result = {};
            }
            if (!oGlobalData.data) {//储存每个板块的国家-机场选择情况，境外、全球有效
                oGlobalData.data = {};
            }
            if (!oGlobalData.country) {//储存国家-机场详细信息，用来生成可操作的机场列别
                oGlobalData.country = [];
                initGolbalCountry(arg.airLineData[2]);//获取全球数据，设置所有国家的机场
            }
            oGlobalData.data[arg.dataIndex] = {};//初期化该板块
            oGlobalData.result[arg.dataIndex] = { 'select': '', 'except': '' };//初期化该板块

            h += '<li><div class="div_lvl_0"><input type="checkbox" value="' + $.trim(d0.Key) + '"/><a href="#dv_0' + hIdSeed + '">' + d0.Label + '</a></div></li>';
            h1 += '<div id="dv_0' + hIdSeed + '" class="tab_lv1"><ul class="_ul1">';//2处的href id ref一致
            var h2 = ''; //境内：机场列表，境外全球：国家列表
            if (arg.airLineFilters == arg.domesticKey) {//境内
                h += '<li><div class="topTip">点击省份可以快速选中或取消机场</div></li>';
                h += '<li class="transTip" style="display:none"><div class="topTip">指定中转点只能直接勾选特定的国家或者机场</div></li>';
                for (var w = 0; w < d0.Data.length; w++) {
                    var d1 = d0.Data[w];
                    hIdSeed = arg.idSeed + '_' + i + '_' + w;
                    h1 += '<li><div class="div_lvl_1" style="display:none;"><input type="checkbox" value="' + $.trim(d1.Key) + '"/><a href="#dv_1' + hIdSeed + '">' + d1.Label + '</a></div></li>';//全国
                    h2 += '<div id="dv_1' + hIdSeed + '" class="tab_lv2">';//3处的href id ref一致
                    for (var x = 0; x < d1.Data.length; x++) {
                        var d2 = d1.Data[x];
                        var bg = '';
                        if (x % 2) {
                            bg = 'background-color: #e5f1ff';
                        }
                        h2 += '<table class="air_list_li" style="width: 100%;">';
                        h2 += '<tr style="' + bg + '"><td class="td1" style="width: 80px;text-align: center"><span>' + d2.Label + '</span></td><td>';//省
                        for (var y = 0; y < d2.Data.length; y++) {
                            var d3 = d2.Data[y];//机场
                            var txt = arg.airPortText($.trim(d3.Key), d3.Label);
                            h2 += '<label style="" title="' + txt + '"><input class="air_list_ipt" type="checkbox" value="' + $.trim(d3.Key) + '"/> ' + txt + '</label>';
                        }
                        h2 += '</td></tr></table>';
                    }
                    h2 += '</div>';
                }
            } else {//境外，全球
                //h += '<li><div class="tab_search tab_search_country"><input type="text"id="txt_s1' + arg.idSeed + '" data-empty="请输入国家二字码" maxlength="2" class="' + arg.searchInputClass + '" /><span class="'
                //    + arg.searchClass + '"><input type="button" a="s1" value="查找"/></span></div></li>';
                h += '<li><div class="topTip">点击区域（如：东亚）可以快速选中国家或取消国家，点击国家可以查看该国家的机场</div></li>';
                h += '<li class="transTip" style="display:none"><div class="topTip">指定中转点只能直接勾选特定的国家或者机场</div></li>';
                ha += '<div class="tab_lv4">';
                for (var w = 0; w < d0.Data.length; w++) {
                    var d1 = d0.Data[w];
                    hIdSeed = arg.idSeed + '_' + i + '_' + w;
                    h1 += '<li><div class="div_lvl_1"><input type="checkbox" value="' + $.trim(d1.Key) + '"/><a href="#dv_1' + hIdSeed + '">' + d1.Label + '</a></div></li>';//洲际
                    h2 += '<div id="dv_1' + hIdSeed + '" class="tab_lv2">';//3处的href id ref一致
                    for (var x = 0; x < d1.Data.length; x++) {
                        var d2 = d1.Data[x];//区域
                        hIdSeed = arg.idSeed + '_' + i + '_' + w + '_' + x;
                        var bg = '';
                        if (x % 2) {
                            bg = 'background-color: #e5f1ff';
                        }
                        h2 += '<table class="air_list_li" style="width: 100%;">';
                        h2 += '<tr style="' + bg + '"><td class="td1" style="width: 80px;text-align: center"><span>' + d2.Label + '</span></td><td>';
                        for (var y = 0; y < d2.Data.length; y++) {
                            var d3 = d2.Data[y];//国家
                            hIdSeed = arg.idSeed + '_' + i + '_' + w + '_' + x + '_' + y;
                            var txt = arg.airPortText($.trim(d3.Key), d3.Label);
                            var countryhref = 'dv_4' + hIdSeed + '_' + $.trim(d3.Key);
                            h2 += '<div class="countryline">';
                            h2 += '<input type="checkbox" value="' + $.trim(d3.Key) + '" ref="' + countryhref + '"/>';
                            h2 += '<span class="air_list_span" ref="' + countryhref + '" key="' + d3.Key + '" label="' + d3.Label + '">' + txt + '</span>';
                            h2 += '<span style="font-weight:bold;display:none">*</span>';
                            h2 += '</div>';
                            initGolbalData(arg.dataIndex, d3);//初期化国家-机场结构
                        }
                        h2 += '</td></tr></table>';
                    }
                    h2 += '</div>';
                }
                ha += '</div>';
            }
            h1 += '</ul>' + h2 + '</div>';
            //}
            var sortAllAirports = new Array();
            for (var i = 0; i < allAirports.length; i++) {
                sortAllAirports = sortAllAirports.concat(allAirports[i]);
            }
            sortAllAirports.sort(function (x, y) {
                if (x.A >= y.A) {
                    return 1;
                }
                else {
                    return -1;
                }
            });
            //获取char与sortAllAirports的对应关系
            //for (var i = 0; i < sortAllAirports.length; i++) {
            //    console.info(sortAllAirports[i].A);
            //}
            var charIndexArray = new Array();
            var nowSIdx = 0;
            var fNums = 0;
            var pFNums;
            for (var i = 65; i <= 90; i++) {//A-Z
                var charIdx = -1;
                pFNums = fNums;
                for (var j = nowSIdx; j < sortAllAirports.length; j++) {
                    nowSIdx++;
                    var charInter = sortAllAirports[j].A.charCodeAt(0);
                    if (charIdx == -1 && charInter == i) {
                        charIdx = j;
                    }
                    if (i < charInter) {
                        nowSIdx--;
                        if (charIdx == -1) {
                            charIdx = nowSIdx;
                        }
                        break;
                    }
                    if (sortAllAirports[j].F) {
                        fNums++;
                    }
                }
                //console.info("Char:" + String.fromCharCode(i) + ' Index:' + charIdx + ' FilterNumbers:' + pFNums);
                charIndexArray.push({ I: charIdx, F: pFNums });
            }
            $(container).data('aaps', sortAllAirports);
            $(container).data('cIdxs', charIndexArray);
            h += '</ul>' + h1;
            h += ha;
            var hc = '';
            hc += '<dl ref="select"><dt>已选</dt><dd></dd></dl>';
            hc += '<dl ref="except"><dt>排除</dt><dd></dd></dl>';
            hc += '<dl ref="unKnown"><dt>未知</dt><dd></dd></dl>';
            if (arg.airLineFilters == arg.domesticKey) {//境内
                h += '<div class="tab_search tab_search_airport"><input type="text"id="txt_s' + arg.idSeed + '" data-empty="请输入机场三字码" maxlength="3" class="' + arg.searchInputClass + '" /><span class="'
                            + arg.searchClass + '"><input type="button" a="s" value="查找"/></span><span class="fastsearch fastsearchAirport">快速选择机场</span></div>';
            } else {
                h += '<div class="tab_search tab_search_country_airport"><input type="text"id="txt_s' + arg.idSeed + '" data-empty="请输入国家二字码或机场三字码" maxlength="3" class="' + arg.searchInputClass + '" /><span class="'
                            + arg.searchClass + '"><input type="button" a="s" value="查找"/></span><span class="fastsearch fastsearchAirport">快速选择机场</span></div>';
            }
            h += '<div class="tab_selected"><div class="mt"><span vu="展开选中机场" vl="收起选中机场">展开选中机场</span><span>清除选中机场</span><div style="background-color: #e5f1ff"><font>您还没选择机场</font>'
                        + hc + '</div></div></div>';
            if (arg.cabinEnabled) {
                h += '<div class="tab_cabin"><div class="head">舱位</div><div class="mt">';
                var ca = arg.cabinData;
                for (var i = 65; i <= 90; i++) {
                    var c = String.fromCharCode(i);
                    var spe = false;
                    for (var j = 0; j < ca.length; j++) {
                        if (ca[j] == c) {
                            spe = true;
                            break;
                        }
                    }
                    h += '<label class="' + (spe ? 'special' : '') + '"><input type="checkbox" value="' + c + '"/> ' + c + '</label>';
                }
                h += '<div class="tab_search tab_search_cabin"><span class="'
                        + arg.allSelectedClass + '"><input type="button" a="ac" value="全选"/></span><span class="'
                        + arg.reverseSelectedClass + '"><input type="button" a="rc" value="反选"/></span><span class="'
                        + arg.searchClass + '"><input type="button" a="cc" value="清空"/></span><span class="fastsearch">快速选择舱位</span><div class="sc" ep="您还没选择舱位">您还没选择舱位</div></div>';
                h += '</div></div>';
            }
            h += '</div></div>';
            //console.info(h);
            container.html(h).find('ul._ul1').idTabs(); //选项卡init
            container.find('.div_lvl_0').find(':checkbox').click(function () {//点击境内/境外/全球选框
                topChkClick($(this).is(':checked'));
            });
            container.find('.div_lvl_1 a').click(function () {//点击洲际标签
                hideAirports();
            });
            container.find('._ul1').find('input:checkbox').click(function () {//点击洲际选框
                var ref = $(this).next().attr('href');
                var isCheck = $(this).is(':checked');
                container.find(ref).find(':checkbox').attr('checked', isCheck);
                container.find(ref).find('.air_list_li .td1 span').attr('data-type', isCheck ? 'on' : 'not');

                var countrys = getCheckBoxValues(ref);
                updateOSelectExcept({ 'type': 'country', 'isCheck': isCheck, 'values': countrys });
                setView();
                updateSelectMark();
                hideAirports();
            });
            
            //默认展示机场            
            container.find('div.tab_selected').find('div.mt').find('span').each(function (i, n) {
                if (i == 0) {
                    $(n).parent().find('div:eq(0)').show();
                    $(n).text($(n).attr('vl'));
                }
            });            
            container.find('span.air_list_span').click(function () {//点击国家名称显隐机场选框 境外全球
                if (getDataType() != '0') {                   
                    $(this).removeClass(arg.hightClass);
                }
                var countryId = $(this).attr('key');
                if (container.find('.air_list_country').attr('key') == countryId) {//已经展开该国家机场，则不处理
                    return;
                }
                setAirport(countryId);
            });
            container.find('.tab_lv2').find(':checkbox').click(function () {//点击国家单选框全选/取消国家全部机场
                if (getDataType() == '0') {//境内
                    $(this).parent().removeClass(arg.hightClass);
                } else {
                    $(this).next().removeClass(arg.hightClass);
                }

                var isCheck = $(this).is(":checked");
                var countryId = $(this).attr('value');

                updateOSelectExcept({ 'type': 'country', 'isCheck': isCheck, 'values': countryId });                
                setView();
                updateSelectMark();

                var oldCountryId = container.find('.air_list_country').attr('key');
                hideAirports();
                if (oldCountryId == countryId) {
                    setAirport(countryId);
                }
            });
            container.find('.tab_lv4').find(':checkbox').live('click', function () {//点击/取消机场
                $(this).parent().removeClass(arg.hightClass);
                var isCheck = $(this).is(":checked");

                updateOSelectExcept({ 'type': 'airport', 'isCheck': isCheck, 'values': $(this).attr('value') });
                setView();
                updateSelectMark();
            });

            //var ipt1 = $('#txt_s1' + arg.idSeed);//快速查找国家输入框
            //ipt1.emptyValue();

            container.find('div.tab_search_country').find(':button').click(function () {//快速查找国家
                container.find('div.tab_lv2 span.air_list_span').removeClass(arg.hightClass);
                var v = $.trim(ipt1.val()).toUpperCase();
                if (v != '' && /^[a-zA-Z]{2}$/g.test(v)) {
                    var span = $('.tab_lv2 span.air_list_span', container).filter(function () {
                        return $(this).attr('key') == v || $(this).attr('label') == v;
                    });
                    if (span.length == 0) {
                        alert('很抱歉，未能找到该国家');
                        return;
                    }
                    if (!span.is(':visible')) {
                        var id = span.parents('div.tab_lv2').attr('id');
                        container.find('.tab_lv1 ._ul1 a[href="#' + id + '"]').click();
                    }
                    span.addClass(arg.hightClass);
                    span.prev().focus();

                    hideAirports();
                }
            });

            container.find('.tab_lv2').find('span.air_list_span').hover(//国家名称悬浮事件
                function () {
                    $(this).addClass('air_list_span_hover');
                },
                function () {
                    $(this).removeClass('air_list_span_hover');
                }
            );

            container.find('.div_lvl_0').find('a').click(function () {//境内名称点击事件
                if ($(this).attr('loaded')) {//底层jquery加载时调用了点击，所以跳过第一次点击事件
                    if ($(this).prev().is(':checked')) {//反选单选框
                        $(this).prev().removeAttr('checked');
                    } else {
                        $(this).prev().attr('checked', 'checked');
                    }
                    topChkClick($(this).prev().is(':checked'));//单选框事件
                } else {
                    $(this).attr('loaded', true);
                }
            });

            container.find('ul._ul0').idTabs(function (id) {//选项卡init，并且根据id确认点击事件
                var dv = $(id).parent().find('div.tab_selected:eq(0)>div>div');
                dv.find('>*').hide();
                var has = false;
                $(id + ' ul._ul1 a').each(function (i, n) {
                    if ($(n).text().indexOf('*') > 0) {
                        has = true;
                        return false;
                    }
                });
                var uk = dv.find('dd[ref=unknowAP]').text() != '';
                if (has || uk) {
                    if (has) {
                        dv.find('dl[ref=' + id + ']').show();
                    }
                    if (uk) {
                        dv.find('[ref=unknowAP]').show();
                    }
                }
                else {
                    dv.find('>font:eq(0)').show();
                }
                var spall = $('div.tab_selected>div.mt>span:eq(2)', container);
                var txt = $('a[href$=' + id + ']').text();
                spall.html('全选' + txt + '机场');
                return true;
            });
            var ipt = $('#txt_s' + arg.idSeed);
            ipt.emptyValue();
            container.find('div.tab_cabin :checkbox').click(function () {//舱位复选框被点击时的事件
                getSelectedCabinText();
            });
            $('span.fastsearchAirport', container).click(function () {//快速选择机场
                arg.onFastAirPortSelected();
            });
            
            container.find('div.tab_search_airport').find(':button').click(function () {//查找机场
                removeHightClass();
                var v = $.trim(ipt.val()).toUpperCase();
                if (v != '' && /^[a-zA-Z]{3}$/g.test(v)) {
                    searchAirport(v);
                } else {
                    alert('请输入正确的机场三字码');
                }
            });

            container.find('div.tab_search_country_airport').find(':button').click(function () {//查找国家+机场
                removeHightClass();
                var v = $.trim(ipt.val()).toUpperCase();
                if (v != '' && /^[a-zA-Z]{3}$/g.test(v)) {
                    searchAirport(v);
                } else if (v != '' && /^[a-zA-Z]{2}$/g.test(v)) {
                    searchCountry(v);
                } else {
                    alert('请输入正确的国家二字码或机场三字码');
                }
            });

            function removeHightClass() {
                if (getDataType() == '0') {
                    container.find('div.tab_lv2 .air_list_ipt').parent().removeClass(arg.hightClass);
                } else {
                    container.find('div.tab_lv4 .air_list_ipt').parent().removeClass(arg.hightClass);
                    container.find('div.tab_lv2 span.air_list_span').removeClass(arg.hightClass);
                }
            }

            function searchAirport(v) {
                if (!oGlobalData.airport[v]) {
                    alert('很抱歉，未能找到该三字码对应的机场');
                    return;
                }
                var dataType = getDataType();
                var countryId = oGlobalData.airport[v];
                switch (dataType) {
                    case '0':
                        if (countryId != 'CN') {
                            alert('很抱歉，未能找到该三字码对应的机场');
                            return;
                        }
                        var chk = container.find('.tab_lv2').find('input:checkbox[value="' + v + '"]');
                        var label = chk.parent();
                        label.addClass(arg.hightClass);
                        chk.focus();
                        break;
                    case '1':
                        if (countryId == 'CN') {
                            alert('很抱歉，未能找到该三字码对应的机场');
                            return;
                        }
                    case '2':
                        var span = $('.tab_lv2 span.air_list_span', container).filter(function () {
                            return $(this).attr('key') == countryId;
                        });
                        if (span.length == 0) {
                            return;
                        }
                        if (!span.is(':visible')) {
                            var id = span.parents('div.tab_lv2').attr('id');
                            container.find('.tab_lv1 ._ul1 a[href="#' + id + '"]').click();
                        }

                        hideAirports();
                        setAirport(countryId);

                        var chk = container.find('.tab_lv4').find('input:checkbox[value="' + v + '"]');
                        var label = chk.parent();
                        label.addClass(arg.hightClass);
                        chk.focus();

                        break;
                }                
            }
            function searchCountry(v) {
                var span = $('.tab_lv2 span.air_list_span', container).filter(function () {
                    return $(this).attr('key') == v || $(this).attr('label') == v;
                });
                if (span.length == 0) {
                    alert('很抱歉，未能找到该国家');
                    return;
                }
                if (!span.is(':visible')) {
                    var id = span.parents('div.tab_lv2').attr('id');
                    container.find('.tab_lv1 ._ul1 a[href="#' + id + '"]').click();
                }
                span.addClass(arg.hightClass);
                span.prev().focus();

                hideAirports();
            }

            $('div.tab_selected>div.mt>span', container).each(function (i, n) {
                switch (i) {
                    case 0: //展开选中机场
                        $(n).click(function () {
                            if ($(this).text() == $(this).attr('vu')) {
                                $(this).parent().find('div:eq(0)').show();
                                $(this).text($(this).attr('vl'));
                            }
                            else {
                                $(this).parent().find('div:eq(0)').hide();
                                $(this).text($(this).attr('vu'));
                            }
                        });
                        break;
                    case 1: //清除选中机场
                        $(n).click(function () {
                            container.find('.div_lvl_0').find(':checkbox').removeAttr('checked');
                            topChkClick(false);
                        });
                        break;
                    case 2: //全选境内机场
                        $(n).click(function () {
                            var dv0 = $('ul._ul0 a.selected', container).attr('href');
                            dv0 = dv0.substr(dv0.indexOf('#'));
                            $(':checkbox', dv0).attr('checked', 'checked');
                            $('div.tab_lv2', dv0).each(function (i, n) {
                                $(':checkbox:checked:eq(0)', n).click().attr('checked', 'checked');

                            });
                        });
                        break;
                }
            });
            $('.air_list_li .td1 span', container).click(function () {//选择省份、区域
                if (container.find('div.tab_lv0').attr('dataIndex') == 'T' && isTopChecked()) {
                    return;
                }
                var isSelect = $(this).attr('data-type');
                var values = '';
                $(this).parents('.air_list_li').find('input:checkbox').each(function (i, n) {
                    values += $(n).attr('value') + '/';
                });

                if (isSelect != 'on') {
                    $(this).parent().parent().find(':checkbox').attr('checked', 'checked');
                    updateOSelectExcept({ 'type': 'country', 'isCheck': true, 'values': values });
                    $(this).attr('data-type', 'on');
                    setView();
                    hideAirports();
                    updateSelectMark();
                } else {
                    $(this).parent().parent().find(':checkbox').removeAttr('checked');
                    updateOSelectExcept({ 'type': 'country', 'isCheck': false, 'values': values });
                    $(this).attr('data-type', 'not');
                    setView();
                    hideAirports();
                    updateSelectMark();
                }
            });
            if (arg.cabinEnabled) {//舱位
                $('div.tab_search_cabin span:last', container).click(function () {//快速选择舱位
                    arg.onFastCabinSelected();
                });
                $('div.tab_search_cabin :button', container).click(function () {
                    var p = $(this).parent().parent().parent();
                    switch ($(this).attr('a')) {
                        case 'ac': //全选舱位
                            chkAll(p);
                            break;
                        case 'rc': //反选舱位
                            rchkAll(p);
                            break;
                        case 'cc': //清空舱位
                            clrChkAll(p);
                            break;
                    }
                    getSelectedCabinText();
                });
            }
            //设置文字CSS
            if (getDataType() == '0') {//中国境内4个字过长，重新设置位置
                container.find('.div_lvl_0 input:checkbox').css({
                    'left': '10px'
                });
            }
        }
        function getSelectedCabinText() {
            var h = $(container).airPortSelect('', 'getSelectedCabin');
            var dsc = container.find('div.tab_cabin div.sc');
            if (h == '') {
                h = dsc.attr('ep');
            }
            dsc.html(h);
        }
        function chkAll(dv) {
            dv.find(':checkbox').attr('checked', 'checked');
        }
        function clrChkAll(dv) {
            dv.find(':checkbox').removeAttr('checked');
        }
        function rchkAll(dv) {
            dv.find(':checkbox').each(function (i, n) {
                if ($(n)[0].checked) {
                    $(n).removeAttr('checked');
                }
                else {
                    $(n).attr('checked', 'checked');
                }
            });
        }
        function updateSelectedTip(dv, check) {
            var id = dv.attr('id');
            if (id == undefined)
                id = dv.parent().parent().parent().attr('id');
            var na = $('a[href$=#' + id + ']');
            var t = na.text().replace('*', '');
            var chks = dv.find(':checked');
            var fp = dv.parent().parent().parent().find('div.tab_selected:eq(0)>div>div');
            var p;
            var f = fp.find('>font');
            if (chks.length > 0) {
                t += '*';
                var h = '';
                for (var i = 0; i < chks.length; i++) {
                    h += $(chks[i]).val() + '/';
                }
                p = $('dl [ref=#' + id + ']', fp).show().filter('dd').html(h).parent();
                if (!check || dv.parent().is(':visible')) {
                    p.show();
                    f.hide();
                }
            }
            else {
                p = $('dl [ref=#' + id + ']', fp).hide().filter('dd').html('').parent();
                if (p.find('dd:contains(/)').length == 0) {
                    p.hide();
                    if (p.parent().find('dd[ref=unknowAP]').text() == '') {
                        f.show();
                    }
                }
            }
            na.html(t);
        }
        function getSelectedArea() {//获取当前选中的class为tab_lv2的div内容
            var hr = container.find('ul._ul0 a.selected').attr('href');
            var hr1 = $(hr.substr(hr.indexOf('#')) + ' ul._ul1 a.selected').attr('href');
            return $(hr1.substr(hr1.indexOf('#')));
        }

        function getArray(airportData) {
            var arr = new Array();
            for (var i = 0; i < airportData.Data.length; i++) {
                if (airportData.Data[i].Data == null) {
                    arr.push({ 'A': $.trim(airportData.Data[i].Key), "F": false });
                }
                else {
                    arr = arr.concat(getArray(airportData.Data[i]));
                }
            }
            return arr;
        }
        //顶层点击事件
        function topChkClick(isChecked) {
            container.find('.tab_lv1').find(':checkbox').attr('checked', isChecked);
            container.find('.air_list_li .td1 span').attr('data-type', isChecked ? 'on' : 'not');

            updateOSelectExcept({ 'type': 'top', 'isCheck': isChecked });

            hideAirports();
            updateSelectMark();
            setView();
            setTransDisabled({ 'type': 'top', 'isCheck': isChecked });//中转的场合不能选择排除
        }
        //更新国家，洲际选中标记 *
        function updateSelectMark() {
            if (getDataType() == '0') {
                return;
            }
            var data = getOData();
            container.find('._ul1').find('a').each(function () {
                var txtDelta = $(this).text().replace('*', '');
                var selDelta = false;

                container.find($(this).attr('href')).find(':checkbox').each(function (i, n) {
                    var selCountry = false;

                    var countryId = $(this).attr('value');
                    if (data[countryId].c == '1') {
                        selCountry = true;
                    } else {
                        var country = data[countryId];
                        for (var airportId in country.airports) {
                            if (country.airports[airportId].c == '1') {
                                selCountry = true;
                                break;
                            }
                        }
                    }

                    if (selCountry) {
                        $(this).next().next().css('display', '');
                        selDelta = true;
                    } else {
                        $(this).next().next().css('display', 'none');
                    }
                });

                if (selDelta) {
                    txtDelta += '*';
                }
                $(this).text(txtDelta);
            });
        }
        //转化文字
        function changeView() {
            function getViewText(values) {
                var txt = '';
                var arr = values.split('/');
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i] == '') {
                        continue;
                    }
                    if (arr[i].length == 2) {
                        var countryId = arr[i];
                        txt += oGlobalData.country[countryId].Label + '/';
                    } else if (arr[i].length == 3) {
                        var airportId = arr[i];
                        if (airportId == 'CN0') {
                            txt += '中国境内/';
                        } else if (airportId == 'CN1') {
                            txt += '境外/';
                        } else if (airportId == 'A00') {
                            txt += '全球/';
                        } else {
                            txt += oGlobalData.airportName[airportId] + '/';
                        }
                    }
                }
                return txt;
            }

            var o = getOSelectExcept();            
            return {
                'select': o.select.replace('CN0/', '中国境内/').replace('CN1/', '境外/').replace('A00/', '全球/'),
                'except': o.except
            };
        }
        //更新已选排除
        function setView() {
            var view = changeView();

            var hasSelected = false;
            container.find('.tab_selected').find('font').show();
            container.find('.tab_selected').find('dl').hide();

            if (view.select != '') {
                hasSelected = true;
            }
            container.find('.tab_selected').find('dl[ref=select]').find('dd').show().html(view.select).prev().show().parent().show();
            if (view.except != '') {
                hasSelected = true;
            }
            container.find('.tab_selected').find('dl[ref=except]').find('dd').show().html(view.except).prev().show().parent().show();
            if (hasSelected) {
                container.find('.tab_selected').find('font').hide();
            }
        }
        //设置国家的机场
        function setAirport(countryId) {
            //var testTime = new Date();
            if (getDataType() == '0') {
                return;
            }

            var data = getOData();
            var country = data[countryId];

            var disabledstyle1 = 'style="display:none"';
            var disabledstyle2 = '';
            var warningMsg = '';

            if (country.c == '1') {//国家选中
                disabledstyle1 = ' style="display:block"';
                if (container.find('div.tab_lv0').attr('dataIndex') == 'T') {//中转的场合不能选择排除
                    warningMsg = '指定中转点只能直接勾选特定的国家或者机场';
                    disabledstyle2 = ' disabled="disabled"';
                } else {
                    warningMsg = '取消机场勾选即可排除该机场';
                }
            } else {//国家没选中
                if (isTopChecked()) {//全球 境外选中的场合 排除国家不能选择机场
                    warningMsg = '需先勾选国家，再排除机场';
                    disabledstyle1 = ' style="display:block"';
                    disabledstyle2 = ' disabled="disabled"';
                }
            }

            var ha = '';
            if (oGlobalData.country[countryId]) {
                var d3 = oGlobalData.country[countryId];
                var containerArg = container.data('args');
                var txt3 = containerArg.airPortText($.trim(d3.Key), d3.Label);
                ha += '<div class="air_list_country" key="' + countryId + '"><span class="dv_4title">' + txt3 + '</span>';
                ha += '<span class="dv_4Alert"' + disabledstyle1 + '>' + warningMsg + '</span><table class="countrygrid tb2" style="width: 100%;"><tr>';
                var countryAirportChangeLine = 4;//换行
                var d3DataLength = d3.Data.length;
                for (var k = 0; k < d3DataLength; k++) {
                    var d4 = d3.Data[k];//机场
                    var txt4 = containerArg.airPortText($.trim(d4.Key), d4.Label);
                    if (k != 0 && k % countryAirportChangeLine == 0) {
                        ha += '</tr><tr>';
                    }
                    ha += '<td><label style="" title="' + txt4 + '"><input class="air_list_ipt" type="checkbox" value="' + $.trim(d4.Key) + '" ' + disabledstyle2;
                    if (country.airports[d4.Key].c == '1') {
                        ha += ' checked="checked" ';
                    }
                    ha += '/> ' + txt4 + '</label></td>';
                }
                ha += '</tr></table></div>';
            }
            container.find('.tab_lv4').html(ha);

            //alert(new Date() - testTime);
        }
        //得到输出的存和除
        function getOSelectExcept() {
            var dataIndex = container.find('div.tab_lv0').attr('dataIndex');
            return oGlobalData.result[dataIndex];
        }
        //得到储存的选中情况
        function getOData() {
            var dataIndex = container.find('div.tab_lv0').attr('dataIndex');
            return oGlobalData.data[dataIndex];
        }
        //解析数据库中的值
        function parseSelectExceptCode(s) {
            var topCode = '';
            var countryArray = new Array();
            var airportArray = new Array();
            var arr = s.split(/[\/]/g);
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] == '') {
                    continue;
                }
                if (arr[i] == getTopCode()) {
                    topCode = arr[i];
                } else if (arr[i].length == 2) {
                    countryArray.push(arr[i]);
                } else if (arr[i].length == 3) {
                    airportArray.push(arr[i]);
                }
            }
            return { 'topCode': topCode, 'countryArray': countryArray, 'airportArray': airportArray };
        }
        //顶层CODE
        function getTopCode() {
            var staticTopCode = '';
            var dataType = getDataType();
            if (dataType == '0') {//境内
                staticTopCode = 'CN0';
            } else if (dataType == '1') {//境外
                staticTopCode = 'CN1';
            } else if (dataType == '2') {//全球
                staticTopCode = 'A00';
            }
            return staticTopCode;
        }
        //表单类型 0境内1境外2全球
        function getDataType() {
            return container.find('div.tab_lv0').attr('dataType');
        }
        //顶层是否选中
        function isTopChecked() {
            return container.find('.div_lvl_0').find(':checkbox').is(':checked');
        }
        //机场所属国家
        function initGolbalCountry(allData) {
            if (!oGlobalData.airport) {//储存机场-国家，方便查找
                oGlobalData.airport = {};
            }
            if (!oGlobalData.airportName) {//储存机场-名称，方便显示
                oGlobalData.airportName = {};
            }
            for (var i = 0; i < allData.Data.length; i++) {
                var delta = allData.Data[i];
                for (var j = 0; j < delta.Data.length; j++) {
                    var region = delta.Data[j];
                    for (var k = 0; k < region.Data.length; k++) {
                        var country = region.Data[k];
                        if (!oGlobalData.country[country.Key]) {
                            oGlobalData.country[country.Key] = country;//国家-机场
                            var airports = country.Data;
                            for (var m = 0; m < airports.length; m++) {
                                oGlobalData.airport[airports[m].Key] = country.Key;//机场-国家
                                oGlobalData.airportName[airports[m].Key] = airports[m].Label;//机场-名称
                            }
                        }
                    }
                }
            }
        }
        //初期化储存的值
        function initGolbalData(index, countryData) {
            var data = oGlobalData.data[index];
            var country = { 'c': 0, airports: {}};
            for (var i = 0; i < countryData.Data.length; i++) {
                var airport = countryData.Data[i];
                country.airports[airport.Key] = { 'c': 0 };
            }
            data[countryData.Key] = country;
        }
        //设置储存的值 arg:{type:'top'|'country'|'airport',isCheck:true|false,values:'AAA/BBB/',skip}
        function updateOSelectExcept(arg) {//核心处理            

            var oSelectExcept = getOSelectExcept();
            var topChecked = isTopChecked();

            if (getDataType() == '0') {
                if (topChecked) {
                    oSelectExcept.select = getTopCode() + '/';
                    oSelectExcept.except = getCheckBoxValues('.tab_lv2', false);
                } else {
                    oSelectExcept.select = getCheckBoxValues('.tab_lv2', true);
                    oSelectExcept.except = '';
                }
            } else {
                arg.isCheck = arg.isCheck ? 1 : 0;
                var data = getOData();

                if (arg.type == 'top') {
                    for (var countryKey in data) {
                        var country = data[countryKey];
                        country.c = arg.isCheck;
                        for (var airportKey in country.airports) {
                            var airport = country.airports[airportKey];
                            airport.c = arg.isCheck;
                        }
                    }
                } else if (arg.type == 'country') {
                    var arr = arg.values.split(/[\/]/g);
                    for (var i = 0; i < arr.length; i++) {
                        if (arr[i] == '') {
                            continue;
                        }
                        var countryKey = arr[i];
                        var country = data[countryKey];
                        if (!country) {
                            continue;//非法的国家
                        }
                        country.c = arg.isCheck;
                        for (var airportKey in country.airports) {
                            var airport = country.airports[airportKey];
                            airport.c = arg.isCheck;
                        }
                    }
                } else if (arg.type == 'airport') {
                    var arr = arg.values.split(/[\/]/g);
                    for (var i = 0; i < arr.length; i++) {
                        if (arr[i] == '') {
                            continue;
                        }
                        var airportKey = arr[i];
                        var countryKey = oGlobalData.airport[airportKey];
                        if (!countryKey) {
                            continue;//非法的机场
                        }
                        var country = data[countryKey];
                        if (!country) {
                            continue;//境外的场合出现中国机场，疑似非法数据，跳过
                        }
                        var airport = country.airports[airportKey];
                        airport.c = arg.isCheck;
                    }
                }

                if (arg.skip === true) {
                    return;
                }

                if (topChecked) {
                    oSelectExcept.select = getTopCode() + '/';
                    oSelectExcept.except = '';
                    var airportExcept = '';
                    for (var countryKey in data) {
                        var country = data[countryKey];
                        if (country.c == '0') {
                            oSelectExcept.except += countryKey + '/';
                        }
                        else {
                            for (var airportKey in country.airports) {
                                var airport = country.airports[airportKey];
                                if (airport.c == '0') {
                                    airportExcept += airportKey + '/';
                                }
                            }
                        }
                    }
                    oSelectExcept.except += airportExcept;
                } else {
                    oSelectExcept.select = '';
                    oSelectExcept.except = '';
                    var airportSelect = '';
                    var airportExcept = '';
                    for (var countryKey in data) {
                        var country = data[countryKey];
                        if (country.c == '1') {
                            oSelectExcept.select += countryKey + '/';
                            for (var airportKey in country.airports) {
                                var airport = country.airports[airportKey];
                                if (airport.c == '0') {
                                    airportExcept += airportKey + '/';
                                }
                            }
                        }
                        else {
                            for (var airportKey in country.airports) {
                                var airport = country.airports[airportKey];
                                if (airport.c == '1') {
                                    airportSelect += airportKey + '/';
                                }
                            }
                        }
                    }
                    oSelectExcept.select += airportSelect;
                    oSelectExcept.except += airportExcept;
                }                
            }
            oSelectExcept.select += container.find('div.tab_selected').find('dl[ref=unKnown]').find('dd').html();
        }
        //获取选择的CHECKBOX值
        function getCheckBoxValues(selector, isChecked) {
            var v = '';
            var attr = '';
            if (isChecked === true) {
                attr = ':checked';
            } else if (isChecked === false) {
                attr = ':not(:checked)';
            }
            container.find(selector).find('input:checkbox' + attr).each(function (i, n) {
                v += $(n).attr('value') + '/';
            });
            return v;
        }        
        //排序后选择
        function sortedCheck(values, chks, needChecked) {
            if (values.length == 0) {
                return;
            }
            chks.sort(function (x, y) {
                if (x.value >= y.value) {
                    return 1;
                }
                else {
                    return -1;
                }
            });
            values.sort(function (x, y) {
                if (x >= y) {
                    return 1;
                }
                else {
                    return -1;
                }
            });
            var index = 0;
            var unKnown = '';
            for (var i = 0; i < values.length; i++) {
                var code = values[i];
                if (index >= chks.length) {
                    unKnown += code + '/';
                } else {
                    for (var j = index; j < chks.length; j++) {
                        if (code == chks[j].value) {
                            if (needChecked) {
                                $(chks[j]).attr('checked', 'checked');
                            } else {
                                $(chks[j]).removeAttr('checked', 'checked');
                            }
                            index = j + 1;
                            break;
                        } else if (code > chks[j].value) {
                            if (j + 1 < chks.length) {//后面还有值
                                if (code < chks[j + 1].value) {//夹值
                                    unKnown += code + '/';
                                    index = j;
                                    break;
                                } else {
                                    //check next
                                }
                            } else {//越界
                                unKnown += code + '/';
                                index = chks.length;
                                break;
                            }
                        } else {//未及
                            unKnown += code + '/';
                            index = j;
                            break;
                        }
                    }
                }
            }
            return unKnown;
        }
        function hideAirports() {
            container.find('.tab_lv4').empty();
        }
        //中转的场合不能选择排除 arg:{type:'top'|'country',isCheck:true|false,values:'AAA/BBB/'}
        function setTransDisabled(arg) {
            var dataIndex = container.find('div.tab_lv0').attr('dataIndex');
            if (dataIndex != 'T') {
                return;
            }
            if (arg.type == 'top') {
                if (arg.isCheck) {
                    container.find('.tab_lv1').find(':checkbox').attr('disabled', 'disabled');
                    container.find('.transTip').css('display', 'block');
                } else {
                    container.find('.tab_lv1').find(':checkbox').removeAttr('disabled');
                    container.find('.transTip').css('display', 'none');
                }
            }

        }
    }
})(jQuery);

(function ($) {
    $.fn.dateRange = function (arg, method) {
        var container = $(this);
        var setting = {
            inputClass: '', //日期输入框样式
            minDate: ''//允许的最小日期
        };
        if (typeof method == "string") {
            switch (method) {
                case 'getValue': //获取设定的日期范围，可以为null或数组[{Start:Date,End:Date}]
                    return container.data('range');
                    break;
                case 'setValue': //设定要初始化的日期范围，数组[{Start:Date,End:Date}]
                    initDateLink(arg);
                    break;
                case 'valiDate': //验证添加的日期值是否在指定日期范围内
                    var vali = true;
                    var arr = container.data('range');
                    if (arr != null && arr.length > 0) {
                        arg = $.extend({}, { minDate: '', maxDate: '' }, arg);
                        var dt = C.Parse.parseDate(arg.minDate);
                        if (dt != null) {
                            vali = vali && dt <= arr[0].Start;
                        }
                        dt = C.Parse.parseDate(arg.maxDate);
                        if (dt != null) {
                            vali = vali && dt >= arr[arr.length - 1].End;
                        }
                    }
                    return vali;
                    break;
            }
        }
        else {
            arg = $.extend({}, setting, arg);
            var h = '<input type="text" class="' + arg.inputClass + '" onclick="WdatePicker({minDate:\'' + arg.minDate + '\',maxDate:$(\'#' + arg.maxDate + '\').val()})"/>'
                    + '<span class="nbs1">—</span>'
                    + '<input type="text" class="' + arg.inputClass + '" onclick="WdatePicker({minDate:\'' + arg.minDate + '\',maxDate:$(\'#' + arg.maxDate + '\').val()})"/>'
                    + '<span class="add1">添加</span><div class="dateRange"></div>';
            container.removeData('range');
            container.html(h).find('span.add1').click(function () {
                var ipt = $(this).parent().find(':text');
                var dt1 = C.Parse.parseDate($(ipt[0]).val());
                var dt2 = C.Parse.parseDate($(ipt[1]).val());
                if (dt1 && dt2) {
                    if (dt1 <= dt2) {
                        var add = true;
                        var rg = container.data('range');
                        if (rg && rg.length > 0) {
                            for (var i = 0; i < rg.length; i++) {
                                var dtr = rg[i];
                                if ((dtr.Start <= dt1 && dtr.End >= dt1)
                                        || (dtr.Start <= dt2 && dtr.End >= dt2)) {
                                    add = false;
                                    break;
                                }
                            }
                        }
                        if (add) {
                            if (!rg) {
                                rg = new Array();
                            }
                            rg.push({ Start: dt1, End: dt2 });
                            initDateLink(rg);
                            ipt.val('');
                        }
                        else {
                            alert('当前日期范围与已选定的日期范围存在冲突');
                        }
                    }
                    else {
                        alert("起始日期应当小于或等于结束日期");
                    }
                }
                else {
                    alert("请先选择日期范围");
                }
            });
        }
        function initDateLink(rg) {
            if (!rg) {
                return;
            }
            rg.sort(function (x, y) {
                return x.Start > y.Start ? 1 : -1;
            });
            container.data('range', rg);
            var ah = '';
            for (var i = 0; i < rg.length; i++) {
                ah += '<a>' + rg[i].Start.pattern('yyyy-MM-dd') + ' — '
                                        + rg[i].End.pattern('yyyy-MM-dd') + '</a>';
            }
            container.find('div').html(ah).find('a').click(function () {
                var prt = $(this).parent();
                var i = prt.find('a').index($(this));
                container.data('range', ArrayDelete(container.data('range'), i));
                $(this).remove();
            });
        }
    }
})(jQuery);

function ArrayDelete(arr, n) {
    if (n < 0) {
        return arr;
    }
    else {
        return arr.slice(0, n).concat(arr.slice(n + 1, arr.length));
    }
}

/**  * emptyValue plugin 默认关键字效果  * @version 1.3  * @authod 雨打浮萍  * Copyright (c) 2012 雨打浮萍 (http://www.rainleaves.com/)  * For more docs and examples visit:  * http://www.rainleaves.com/html/1357.html  */
(function ($) {
    $.fn.val2 = $.fn.val;
    $.fn.emptyValue = function (arg) {
        this.each(function () {
            var input = $(this);
            var options = arg;
            if (typeof options == "string") {
                options = { empty: options }
            }
            options = jQuery.extend(
            {
                empty: input.attr("data-empty") || "",
                className: "gray"
            }, options);
            input.attr("data-empty", options.empty);
            return input.focus(function () {
                $(this).removeClass(options.className);
                if ($(this).val2() == options.empty) { $(this).val2(""); }
            }).blur(function () {
                if ($(this).val2() == "" || $(this).val2() == options.empty || $(this).val2() == $(this).attr("data-empty")) {
                    //$(this).val2(options.empty);
                    $(this).val2($(this).attr("data-empty"));
                    $(this).addClass(options.className);
                } else { $(this).removeClass(options.className); }
            }).blur();
        });
    };
    /*重写jquery val方法，增加data-empty过滤*/
    $.fn.val = function () {
        var value = $(this).val2.apply(this, arguments);
        var empty = $(this).attr("data-empty");
        if (typeof empty != "undefined" && empty == value) {
            value = "";
        }
        return value;
    };
    $.fn.focus2 = function () {
        $(this).focus();
        if ($(this).val() == $(this).attr("data-empty"))
            $(this).val('');
    };
})(jQuery);

/* idTabs ~ Sean Catchpole - Version 2.2 - MIT/GPL */
(function () {
    var dep = { "jQuery": "http://code.jquery.com/jquery-latest.min.js" }; var init = function () {
        (function ($) {
            $.fn.idTabs = function () {
                var s = {}; for (var i = 0; i < arguments.length; ++i) { var a = arguments[i]; switch (a.constructor) { case Object: $.extend(s, a); break; case Boolean: s.change = a; break; case Number: s.start = a; break; case Function: s.click = a; break; case String: if (a.charAt(0) == '.') s.selected = a; else if (a.charAt(0) == '!') s.event = a; else s.start = a; break; } }
                if (typeof s['return'] == "function")
                    s.change = s['return']; return this.each(function () { $.idTabs(this, s); });
            }
            $.idTabs = function (tabs, options) {
                var meta = ($.metadata) ? $(tabs).metadata() : {}; var s = $.extend({}, $.idTabs.settings, meta, options); if (s.selected.charAt(0) == '.') s.selected = s.selected.substr(1); if (s.event.charAt(0) == '!') s.event = s.event.substr(1); if (s.start == null) s.start = -1; var showId = function () {
                    if ($(this).is('.' + s.selected))
                        return s.change; var id = "#" + this.href.split('#')[1]; var aList = []; var idList = []; $("a", tabs).each(function () { if (this.href.match(/#/)) { aList.push(this); idList.push("#" + this.href.split('#')[1]); } }); if (s.click && !s.click.apply(this, [id, idList, tabs, s])) return s.change; for (i in aList) $(aList[i]).removeClass(s.selected); for (i in idList) $(idList[i]).hide(); $(this).addClass(s.selected); $(id).show(); return s.change;
                }
                var list = $("a[href*='#']", tabs).unbind(s.event, showId).bind(s.event, showId); list.each(function () { $("#" + this.href.split('#')[1]).hide(); }); var test = false; if ((test = list.filter('.' + s.selected)).length); else if (typeof s.start == "number" && (test = list.eq(s.start)).length); else if (typeof s.start == "string" && (test = list.filter("[href*='#" + s.start + "']")).length); if (test) { test.removeClass(s.selected); test.trigger(s.event); }
                return s;
            }
            $.idTabs.settings = { start: 0, change: false, click: null, selected: ".selected", event: "!click" }; $.idTabs.version = "2.2"; $(function () { $(".idTabs").idTabs(); });
        })(jQuery);
    }
    var check = function (o, s) { s = s.split('.'); while (o && s.length) o = o[s.shift()]; return o; }
    var head = document.getElementsByTagName("head")[0]; var add = function (url) { var s = document.createElement("script"); s.type = "text/javascript"; s.src = url; head.appendChild(s); }
    var s = document.getElementsByTagName('script'); var src = s[s.length - 1].src; var ok = true; for (d in dep) { if (check(this, d)) continue; ok = false; add(dep[d]); } if (ok) return init(); add(src);
})();

(function ($) {
    $.fn.dropDownList = function (arg, method) {
        var container = $(this);
        var setting = {
            data: [], //键值对集合，格式[{Key:'',Value:''},{Key:'',Value:''}]
            defText: '数据选择',
            onSelect: function (json) { } //如果选择的是默认值，则返回的json为null
        };
        if (typeof method == "string") {
            switch (method) {
                case 'getSelected': //获取选中项对应的键值对{Key:'',Value:''},//如果选择的是默认值，则返回的json为null
                    return container.find('span.sel').data('kv');
                    break
                case 'setSelectedKey': //设置选中项,传入Key值
                    container.find('span[kv=' + arg + ']').click();
                    break;
                default: break;
            }
        }
        else {
            arg = $.extend({}, setting, arg);
            var ipt = $('<input type="text" value="' + arg.defText + '" class="selInput" readonly="readonly" />');
            container.append(ipt);
            var opc = $('<div class="selList" style="display:none;"></div>');
            opc.append('<span class="cur sel">' + arg.defText + '</span>');
            for (var i = 0; i < arg.data.length; i++) {
                var op = $('<span class="cur" kv="' + arg.data[i].Key + '">' + arg.data[i].Value + '</span>');
                op.data('kv', arg.data[i]);
                opc.append(op);
            }
            container.append(opc);
            ipt.mousedown(function () {
                $(this).parent().find('div.selList').show();
            }).blur(function () {
                setTimeout(function () {
                    opc.hide();
                }, 100);
            });
            opc.find('span').hover(function () {
                $(this).addClass('hov');
            },
            function () {
                $(this).removeClass('hov');
            }).mousedown(function () {
                $(this).siblings().removeClass('sel');
                $(this).addClass('sel');
                $(this).parent().hide();
                $(this).parent().parent().find('input.selInput').val($(this).text());
                arg.onSelect($(this).data('kv'));
            });
        }
    }
})(jQuery);

(function ($) {
    $.fn.qqWpa = function (arg) {
        var setting = {
            qq: [],
            linkClass: '',
            imgTitle: ''
        };
        arg = $.extend({}, setting, arg);
        if (arg.qq.length > 0) {
            for (var i = 0; i < arg.qq.length; i++) {
                $(this).append('<a class="' + arg.linkClass + '" target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=' + arg.qq[i] + '&site=qq&menu=yes">'
                    + '<img border="0" src="http://wpa.qq.com/pa?p=2:' + arg.qq[i] + ':41" alt="' + arg.imgTitle + '" title="' + arg.imgTitle + '" /></a>');
            }
        }
    }
})(jQuery);

/* 对Date的扩展，将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new
Date()).pattern("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423
* (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
* (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
* (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
* (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
*/
Date.prototype.pattern = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    var week = {
        "0": "/u65e5",
        "1": "/u4e00",
        "2": "/u4e8c",
        "3": "/u4e09",
        "4": "/u56db",
        "5": "/u4e94",
        "6": "/u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
function FreeInputJElass(p) {
    var input = $('#' + p.input);
    var hidden = $('#' + p.hidden);
    if (FreeInputJElassReg(input.val())) {
        jElass.exec({
            input: p.input,
            hidden: p.hidden,
            url: p.url,
            error: p.hintMsg,
            width: 0,
            canFreeInput: true,
            bak: function (key, name) {
                if (!FreeInputJElassReg(key) || hidden.val() == p.defaultValue) {
                    input.val('');
                    hidden.val('');
                }
                if (input.val() == '' && input.attr("data-empty")) {
                    input.val2(input.attr("data-empty"));
                    input.addClass('gray');
                }
            }
        });
    } else {
        input.val('');
        hidden.val('');
    }
    function FreeInputJElassReg(value) {
        if (!p.regTxt) {
            return true;
        } else {
            return new RegExp(p.regTxt).test(value);
        }
    }
}